package chances.wechat.utils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public abstract class PathUtils {
	static String PATH = "/";
	static char pathChar = PATH.charAt(0);

	public static String getPath(final String path) {
		int idx = path.lastIndexOf(pathChar);
		if (idx > -1) {
			return path.substring(0, idx);
		} else {
			return path;
		}
	}
	
	

	public static String getSubPath(final String path,String name) {
		int idx = path.lastIndexOf(name);
		if (idx > -1) {
			return path.substring(0, idx);
		} else {
			return path;
		}
	}

	public static String join(final String... names) {
		List<String> as = Arrays.asList(names);
		String path = as.stream().map(s -> {
			String result = s;
			int begin = 0;
			int end = result.length();
			if (result.charAt(0) == pathChar) {
				begin = 1;
			}
			if (result.charAt(end - 1) == pathChar) {
				end = end - 1;
			}

			return result.substring(begin, end);

		}).collect(Collectors.joining(PATH));

		if (names[0].charAt(0) == pathChar) {
			return "/" + path;
		} else {
			return path;
		}
	}

	public static String[] split(final String str) {
		String[] vars = str.split(PATH);
		int begin = 0;
		int end = vars.length;
		if (vars[0].length() == 0) {
			begin = 1;
		}
		if (vars[vars.length - 1].length() == 0) {
			end = vars.length - 1;
		}
		return Arrays.copyOfRange(vars, begin, end);
	}

	public static String getName(final String str) {
		int idx = str.lastIndexOf(pathChar);
		if (idx > -1) {
			return str.substring(idx + 1);
		} else {
			return str;
		}
	}
}
